<template>
  <view class="order-list">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="back" @click="goBack">＜</text>
      <text class="title">我的订单</text>
      <view class="right-icons"></view>
    </view>

    <!-- 订单状态标签 -->
    <view class="tabs">
      <view v-for="(tab, index) in tabs" :key="index" 
            :class="['tab-item', currentTab === index ? 'active' : '']"
            @click="switchTab(index)">
        {{ tab }}
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view scroll-y class="order-content">
      <view v-if="loading" class="loading">加载中...</view>
      <view v-else-if="displayOrders.length === 0" class="empty">暂无订单</view>
      <view v-else>
        <view class="order-item" v-for="(order, index) in displayOrders" :key="index">
          <!-- 订单头部 -->
          <view class="order-header">
            <text class="order-number">订单编号：{{ order.orderNum }}</text>
			<view v-if="order.status === '待支付' && order.countdown > 0" class="countdown">
			    剩余支付时间：{{ order.countdown }}秒
			</view>
            <image @click="toOrderDetail(order.status,order)" 
                  class="img" 
                  src="/static/mp/mp箭头.png"
                  mode="aspectFit"></image>
          </view>
        
          <!-- 订单信息 -->
          <view class="order-info">
            <view class="service-item">
              <text class="label">服务项目：</text>
              <text class="value">{{ getServiceName(order.serviceId) || '加载中...' }}</text>
            </view>
            
            <view class="shop-item">
              <text class="label">服务门店：</text>
              <text class="value">{{ getShopName(order.merchantId) || '加载中...' }}</text>
              <image class="img" 
                    src="/static/mp/plane.png"
                    mode="widthFix"></image>
              <text class="order-status">{{ order.status }}</text>
            </view>

            <view class="time-item">
              <text class="label">下单时间：</text>
              <text class="value">{{ order.orderTime || '--' }}</text>
            </view>
          </view>
        
          <!-- 订单底部 -->
          <view class="order-footer">
            <text class="price" 
                  :class="{'orderPrice': ['待支付','待使用'].includes(order.status)}">
              {{ order.status === '待支付' || order.status === '待使用' ? '应付' : '实付' }}：
              ￥{{ order.orderPrice || 0.00 }}
            </text>
            <!-- 操作按钮组 -->
            <view class="action-buttons" v-if="order.buttons && order.buttons.length">
              <button v-for="(btn, btnIndex) in order.buttons" 
                      :key="btnIndex"
                      :class="['action-btn', btn.color]"
                      @click.stop="handleAction(btn.action, order)">
                {{ btn.text }}
              </button>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import request from '../../../uitls/request';

export default {
  data() {
    return {
      tabs: ['全部', '待支付', '待使用', '待评价'],
      currentTab: 0,
      orderList: [],        // 原始订单数据
      displayOrders: [],    // 当前显示的订单数据
      serviceList: [],
      shopList: [],
      loading: true,
      userInfo: null,
      userId:null,
    }
  },
  onunload() {
    uni.$off('updateOrderStatus');
  },
  onLoad(options) {
    uni.$on('updateOrderStatus',()=>{
      this.getOrders();
    })
    const initialTab = options.tab ? 
    this.tabs.findIndex(t => t === options.tab) : 0;
	this.switchTab(initialTab);
    this.getService();
    this.getShop();
  },
  onShow() {
    this.userInfo = uni.getStorageSync('userInfo');
    console.log('当前用户ID:', this.userInfo.id); // 添加调试日志
    this.userId = this.userInfo?.id || null; // 安全访问属性
    if (this.userId) {
        this.getOrders();
    } else {
        console.error('未获取到用户ID');
        uni.redirectTo({ url: '/pages/login/login' }); // 添加未登录处理
    }
    this.switchTab(this.currentTab);
  },
  methods: {
    toOrderDetail(status,order) {
      const routes = {
        '待支付': `/pages/pay/pay?id=${order.id}`,
        '待使用': `/pages/scan/scan?id=${order.id}`,
        '待评价': `/pages/comment/comment?id=${order.id}`
      }
      if (routes[status]) {
        uni.navigateTo({ url: routes[status] })
       success:()=>{
         uni.$emit('updateOrderStatus')
       }
      }
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    enhanceOrders(orderList) {
      return orderList.map(order => {
        switch(order.status) {
          case '待支付':
            order.buttons = [
              { text: '取消订单', action: 'cancel', color: 'gray' },
              { text: '立即支付', action: 'pay', color: 'primary' }
            ];
            break;
          case '待使用':
            order.buttons = [
              { text: '申请退款', action: 'refund', color: 'gray' },
              { text: '扫码结算', action: 'scan', color: 'primary' }
            ];
            break;
          case '待评价':
            order.buttons = [
              { text: '立即评价', action: 'review', color: 'primary' },
              { text: '再来一单', action: 'again', color: 'primary' }
            ];
            break;
          default:
            order.buttons = [];
        }
        return order;
      })
    },
    
    switchTab(index) {
      this.currentTab = index;
      
      if(index === 0) {
        // 显示全部订单
        this.displayOrders = this.enhanceOrders([...this.orderList]);
      } else {
        // 获取对应的状态文本
        const targetStatus = this.tabs[index];
        // 过滤出对应状态的订单
        const filteredOrders = this.orderList.filter(
          order => order.status === targetStatus
        );
        this.displayOrders = this.enhanceOrders(filteredOrders);
      }
    },
    
    handleAction(action, order) {
      switch (action) {
        case 'cancel':  // 取消订单
        uni.showModal({
          title: '确认取消',
          content: '确定要取消该订单吗？',
          success: (res) => {
            if (res.confirm) {
              request({
                url: `/offer/orders/${order.id}`,
                method: 'PUT',
                data: { orderStatus: 3 }, // 状态改为已取消
                success: () => {
                  const index = this.orderList.findIndex(item => item.id === order.id);
                  if (index > -1) {
                    this.orderList[index].status = '已取消';
                    this.switchTab(this.currentTab);
                  }
                }
              });
            }
          }
        });
        break;
        case 'pay':
        request({
        url: `/offer/orders/${order.id}`,
        method: 'PUT',
        data: {
          orderStatus: 1 // 支付成功后状态改为待使用
        },
        success: () => {
          order.status = '待使用';
          uni.$emit('updateOrderStatus')
          this.switchTab(this.currentTab);
          uni.navigateTo({ url: `/pages/pay/pay?id=${order.id}` })
        }
      });
      break;
        case 'scan':
        case 'review':
        this.toOrderDetail(order.status,order)
          break
          case 'refund':
          uni.showModal({
            title: '确认退款',
            content: '确定要申请退款吗？',
            success: (res) => {
              if (res.confirm) {
                request({
                  url: `/offer/orders/${order.id}`,
                  method: 'PUT',
                  data: {
                    orderStatus: 4 
                  },
                  success: () => {
                    const index = this.orderList.findIndex(item => item.id === order.id);
                    if (index > -1) {
                      // 更新状态并设置倒计时
                      this.orderList[index].status = '待支付';
                      this.orderList[index].countdown = 20*60;
                      const timer = setInterval(() => {
                if (this.orderList[index].countdown > 0) {
                  this.orderList[index].countdown--;
                  this.$forceUpdate();
                } else {
                  clearInterval(timer);
                  // ▼ 这里替换原来的删除逻辑 ▼
                  request({
                    url: `/offer/orders/${order.id}`,
                    method: 'PUT',
                    header: {
                      Authorization: uni.getStorageSync('token')
                    },
                    data: { orderStatus: 3 },
                    success: () => {
                      this.orderList[index].status = '已取消';
                      this.switchTab(this.currentTab);
                    }
                  });
                        }
                      }, 1000);
                      this.switchTab(this.currentTab);
                    }
                  }
                });
              }
            }
          });
          break;

      
        case 'again':
          uni.navigateTo({ url: '/pages/order-again/order-again' })
          break
        default:
          uni.showToast({
            title: '未知操作：' + action,
            icon: 'none'
          })
      }
    },
    
    // 订单接口
    getOrders(userId) {
      this.loading = true;
      request({
        url: `/offer/orders/list/`,
        method: 'GET',
        data: {
          pageNum: 1,
          pageSize: 10,
          del:0,
          userId: this.userId
        },
        success: (res) => {
          this.loading = false;
          if(res.data.code === 200) {
            this.orderList = res.data.rows.map(item => ({
              id:item.id,
              orderNum: item.orderNo,
              serviceId: item.serviceId,
              merchantId: item.merchantId,
              orderTime: item.orderTime,
              orderPrice: item.orderPrice,
              status: this.mapOrderStatus(item.orderStatus),
              buttons: []
            }));
            // 初始化显示数据
            this.switchTab(this.currentTab);
          }
        },
        fail: () => {
          this.loading = false;
        }
      })
    },
    
    // 状态映射方法
    mapOrderStatus(status) {
      const statusMap = {
        0: '待支付',
        1: '待使用', 
        2: '待评价',
        3: '已取消',
        4: '已退款',
        5: '已完成'  // 添加状态5的映射
      };
      return statusMap[status] || '未知状态';
    },

    
    getService() {
      request({
        url: '/evaluate/details/list',
        method: 'GET',
        params: {
          pageNum: 1,
          pageSize: 1000
        },
        header: {
          Authorization: uni.getStorageInfoSync('token')
        },
        success: (res) => {
          if(res.data.code === 200) {
            this.serviceList = res.data.rows;
          }
        }
      })
    },
    
    getServiceName(serviceId) {
      const service = this.serviceList.find(item => item.id === serviceId);
      return service ? service.serviceName : '未知服务';
    },
    
    getShop() {
      request({
        url: 'merchant/merchant/list',
        method: "GET",
        params: {
          pageNum: 1,
          pageSize: 10
        },
        header: {
          Authorization: uni.getStorageInfoSync('token')
        },
        success: (res) => {
          if(res.data.code === 200) {
            this.shopList = res.data.rows;
          }
        }
      })
    },
    
    getShopName(id) {
      const shop = this.shopList.find(item => item.id === id);
      return shop ? shop.name : '未知门店';
    }
  }
}
</script>

<style lang="scss">
.red-price {
  color: #e53935 !important;
}

.action-btn {
  // 已有基础样式不动
  &.gray {
    background-color: #ccc !important;
    color: #333 !important;
  }

  &.primary {
    background-color: #1976D2 !important;
    color: #fff !important;
  }
}

.order-list {
  /* #ifdef MP-WEIXIN */
  margin-top: 70rpx;
  /* #endif */
  background: url(/static/mp/背景版.png);
  background-size: 100% 35%;
  background-repeat: no-repeat;
  min-height: 100vh;
  padding-bottom: 100rpx;
  
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 40rpx 30rpx 20rpx 30rpx;
    color: #fff;
  }
  
  .back {
    font-size: 28px;
    margin-right: 10px;
  }
  
  .title {
    font-size: 18px;
  }
  
  .right-icons {
    display: flex;
    gap: 20rpx;
    width: 90rpx;
  }

  .tabs {
    display: flex;
    background-color: transparent;
    padding: 20rpx 0;

    .tab-item {
      flex: 1;
      text-align: center;
      font-size: 28rpx;
      color: #fff;
      position: relative;

      &.active {
        color: #fff;
        font-weight: 500;

        &::after {
          content: '';
          position: absolute;
          bottom: -10rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 80rpx;
          height: 4rpx;
          background-color: #fff;
        }
      }
    }
  }

  .order-content {
    padding: 20rpx;
    width: 95%;
    height: calc(100vh - 240rpx);

    .loading, .empty {
      text-align: center;
      padding: 40rpx;
      color: #999;
    }

    .order-item {
      background-color: #fff;
      border-radius: 12rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

      .order-header {
        display: flex;
        justify-content: space-between;
        padding-bottom: 20rpx;
        border-bottom: 1rpx solid #eee;

        .order-number {
          font-size: 26rpx;
          color: #666;
        }
        .img{
          margin-top: 8rpx;
          width: 20rpx;
          height: 25rpx;
        }
      }

      .order-info {
        padding: 20rpx 0;

        .service-item,
        .shop-item,
        .time-item {
          display: flex;
          margin-bottom: 10rpx;
          font-size: 26rpx;

          .label {
            color: #999;
            width: 140rpx;
          }

          .value {
            color: #333;
            vertical-align: middle;
            flex: 1;
          }

          .order-status {
            font-size: 26rpx;
            color: #1976D2;
            margin-left: auto;
          }
          .img{
            width: 30rpx;
            height: 30rpx;
            vertical-align: middle;
            margin-left: 15rpx;
            margin-top: 6rpx;
          }
        }
      }

      .order-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 20rpx;
        border-top: 1rpx solid #eee;

        .price {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
          
          &.orderPrice {
            color: #e53935;
          }
        }

        .action-buttons {
          display: flex;
          gap: 20rpx;

          .action-btn {
            font-size: 24rpx;
            padding: 10rpx 30rpx;
            border-radius: 30rpx;
            background-color: #1976D2;
            color: #fff;
            width: auto;
            min-width: 120rpx;
            line-height: 1.5;
            margin: 0;
            
            &:active {
              opacity: 0.8;
            }
          }
        }
      }
    }
  }
}
.countdown {
    font-size: 24rpx;
    color: #e53935;
    margin-right: 40px;
}
</style>